/**
 * 打印日志的模块
 */
export default class Observer {
  constructor(el) {
    this.el = document.querySelector(el);
    //初始化日志池
    this.logPool = [];
  }

  /**
   * 更新日志
   * @param {*} type 'get' or 'set'
   * @param {*} key
   * @param {*} oldValue
   * @param {*} newValue
   */
  updateLog(type, key, oldValue, newValue) {
    switch (type) {
      case 'get':
        this.getProp(key, oldValue);
        break;
      case 'set':
        this.setProp(key, oldValue, newValue);
        break;
      default:
        break;
    }
  }

  /**
   * 访问属性的方法
   * @param {*} key
   * @param {*} oldValue
   */
  getProp(key, oldValue) {
    const o = {
      type: 'get',
      dateTime: new Date(),
      key,
      value: oldValue
    };

    this.logPool.push(o);
    this.log(o);
  }

  /**
   * 修改属性的方法
   * @param {*} key
   * @param {*} oldValue
   * @param {*} newValue
   */
  setProp(key, oldValue, newValue) {
    const o = {
      type: 'set',
      dateTime: new Date(),
      key,
      oldValue,
      newValue
    };

    this.logPool.push(o);
    this.log(o);
  }

  /**
   * 处理html模板
   * @param {*} o
   */
  log(o) {
    const { type, dateTime, key } = o;
    const oLi = document.createElement('li');
    let htmlStr = '';

    switch (type) {
      case 'get':
        htmlStr = `
          ${dateTime}:
          I got the key '${key}'.
          The value of the key is ${o.value}.
        `;
        break;
      case 'set':
        htmlStr = `
          ${dateTime}:
          I set the key ${key}'s value '${o.newValue}'
          from the old value ${o.oldValue}.
        `;
        break;
      default:
        break;
    }

    oLi.innerHTML = htmlStr;
    this.el.appendChild(oLi);
    console.log(this.logPool);
  }
}
